<template>
  <el-table :data="books" style="width: 100%">
    <el-table-column prop="author" label="Author" width="180"></el-table-column>
    <el-table-column prop="bookname" label="Bookname" width="180"></el-table-column>
    <el-table-column prop="category" label="Category" width="180"></el-table-column>
    <el-table-column prop="introduction" label="Introduction" width="180"></el-table-column>
    <el-table-column prop="isbn" label="ISBN" width="180"></el-table-column>
    <el-table-column prop="location" label="Location" width="180"></el-table-column>
    <el-table-column prop="press" label="Press" width="180"></el-table-column>
    <el-table-column prop="publishtime" label="Publishtime" width="180"></el-table-column>
    <el-table-column prop="remain" label="Remain" width="180"></el-table-column>
    <el-table-column prop="total" label="Total" width="180"></el-table-column>
    <el-table-column label="Operation" width="180">
      <template slot-scope="scope">
        <el-button type="danger" @click="deleteBook(scope.$index)">Delete</el-button>
      </template>
    </el-table-column>
  </el-table>
</template>

<script>
export default {
  data() {
    return {
      books: [],
      isRunning: true
    };
  },
  created() {
      this.getBooksData();
  },
  mounted() {
    this.interval = setInterval(() => {
      this.getBooksData();
      this.isRunning = true;
    }, 1000); // 设置间隔时间
  },
  beforeDestroy() {
    clearInterval(this.interval); // 清除定时器
  },
  methods: {
    getBooksData() {
    this.$request.get('/book/list', {
    params: {
      keyword: 's'
    }
  })
    .then(res => {
      const booksData = res.data.data;
      this.books = booksData.map(book => ({
        author: book.author,
        bookname: book.bookname,
        category: book.category,
        introduction: book.introduction,
        isbn: book.isbn,
        location: book.location,
        press: book.press,
        publishtime: book.publishtime,
        remain: book.remain,
        total: book.total
      }));
      this.isRunning = false;
    })
    .catch(error => {
      console.log(error);
      alert('Failed！');
    });
},

deleteBook(index) {
  this.$confirm('Are you sure to delete this book?', 'Prompt', {
    confirmButtonText: 'Yes',
    cancelButtonText: 'No',
    type: 'warning'
  })
    .then(() => {
      this.$request
        .get(`/book/delete?isbn=${this.books[index].isbn}`)
        .then((res) => {
          console.log(res);
          if (res.status == 200) {
            alert("Successfully deleted！");
            this.getBooksData();            
          } else {
            alert("Failed！");
          }
        })
        .catch((error) => {
          console.log(error);
          alert("Failed！");
        });
    })
    .catch(() => {
      // 取消删除操作
    });
}
}}

</script>
